#!/bin/bash
inf1=""
inf2=""
succ(){
	if [ "$1" == "0" ];then
		echo " Done." 1>&2
	else
		echo " Failed." 1>&2
		exit 1
	fi
}
getnum(){
	if [ ! -n "$1" ];then
		return 1
	fi
	num="${1##*/}"
	num="${num%%.*}"
	echo "$num"
	unset num
}
getinf(){
	if [ ! -n "$1" ];then
		return 1
	fi
	if [[ ! "$1" == *"imomoe"* ]];then
		succ 1
	fi
	fin="$(getnum "$1")"
	fin="${fin#*-}"
	inf1="${fin%%-*}"
	inf2="${fin#*-}"
	unset fin
}
trydo(){
	if [ ! -n "$1" ];then
		return 1
	fi
	cont="$(curl -s "$1")"
	rvar="$?"
	succ "$rvar"
	echo "$cont"
	unset cont rvar
}
fdjs(){
	if [ ! -n "$1" ];then
		return 1
	fi
	raw="$(echo "$1" | grep "playdata")"
	if [ "$raw" == "" ];then
		succ 1
	fi
	raw="${raw#*src=\"}"
	raw="${raw%%\"*}"
	echo "$raw"
	unset raw
}
basdom(){
	if [ ! -n "$1" ];then
		return 1
	fi
	dom="${1#*://}"
	dom="${dom%%/*}"
	echo "$dom"
	unset dom
}
cutbra() {
	if [ ! -n "$1" ];then
		return 1
	fi
	cur=0
	bra=0
	str=""
	fd=0
	while [ "$cur" != "0" ] || [[ "$cur" == "0" && "$bra" == 0 ]];do
		ch="${1:$fd:1}"
		if [ "$ch" == '[' ];then
			let cur=cur+1
			bra=1
		fi
		if [ "$ch" == ']' ];then
			let cur=cur-1
			bra=1
		fi
		str="${str}${ch}"
		let fd=fd+1
	done
	echo "$str"
	unset cur bra ch fd str
}
anadat(){
	if [ ! -n "$1" ];then
		return 1
	fi
	cont="$(cutbra "$1");"$'\n'"console.log(VideoListJson[$inf1][1][$inf2])"
	node <<< "$cont"
	rvar="$?"
	succ "$rvar"
	unset cont rvar
}
finadd(){
	if [ ! -n "$1" ];then
		return 1
	fi
	addr="${1#*$}"
	addr="${addr%\$*}"
	echo "$addr"
	unset addr
}
askq(){
	if [ ! -n "$1" ];then
		return 2
	fi
	read -p "${1} (y/n) " cho
	if [ "$cho" == "y" ] || [ "$cho" == "Y" ] || [ "$cho" == "yes" ] || [ "$cho" == "Yes" ] || [ "$cho" == "YES" ];then
		return 0
	else
		return 1
	fi
	unset cho
}
if [ ! -n "$1" ];then
	exit 1
fi
echo -n "Getting web page information..."
getinf "$1"
succ 0
echo -n "Getting web page contents..."
con="$(trydo "$1")"
echo -n "Finding web page data..."
add="$(fdjs "$con")"
succ 0
echo -n "Getting web page data..."
add="$(basdom "$1")${add}"
con="$(trydo "$add")"
echo -n "Analyzing web page data..."
tmp="$(anadat "$con")"
echo -n "Finding the download address..."
add="$(finadd "$tmp")"
succ 0
askq "The download address is:"$'\n'"$add"$'\n'"Do you want to download it now?"
if [ "$?" == "0" ];then
	wget -O "$(getnum "$1").mp4" "$add"
fi
exit 0
